package at.ac.tuwien.prog.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import at.ac.tuwien.prog.entity.Register;
import at.ac.tuwien.prog.system.ISystem;

/**
 * 
 * 
 * Lies ein Zeichen von der Tastatur, speichere es in Register A und springe zur Adresse B
 * (schreibe B als Konstante in Register -8192) falls eine Eingabe gemacht wurde, sonst mache nichts.
 *
 * @author christoph.pickl@student.tuwien.ac.at
 */
public class ReadCommand extends AbstractCommand {
	
	private static final Log LOG = LogFactory.getLog(ReadCommand.class);

	public static final String NAME = "read";

	public ReadCommand(int targetStoreAddress, int jumpAddress) {
		super(targetStoreAddress, jumpAddress);
	}

	public void execute(final ISystem system) {
		final int targetStoreAddress = this.getOperand1();
		final Register jumpAddress = Register.newByInt(this.getOperand2()); // only first 14 bits set, but will be used for register value (program counter content) 
		LOG.info("execute(targetStoreAddress="+targetStoreAddress+"; jumpAddress="+jumpAddress+")");
		
		final Integer userInputNumber = system.getMainWindow().readUserInput();
		if(userInputNumber == null) {
			// user aborted prompt
			return;
		}
		
		final Register userInputRegisterValue = Register.newByInt(userInputNumber);
		LOG.debug("Writing userInput=["+userInputRegisterValue+"]");
		system.getMemoryManager().setRegisterValue(targetStoreAddress, userInputRegisterValue);
		system.getMemoryManager().setProgramCounter(jumpAddress);
	}
	

}
